import { Tree, Input, Button , Rate } from 'antd';
import { useEffect, useState } from 'react';
import {FormOutlined, PlusOutlined, MinusOutlined} from '@ant-design/icons';
import Editor from 'for-editor';

const { Search } = Input;

interface IDescriptionData{
    key: string;
    title: string; 
    rate: number;
    content: string;
    length: number;
    isEdit: boolean;
    children?: IDescriptionData []
}

const SkillDescription: React.FC = ()=>{
   
    const [data, setData] = useState<IDescriptionData []>([]);

    // 当前选中的文档
    const [ Currentkey , setCurrentkey ] = useState('');

    useEffect(() => {
        if(data.length && Currentkey)
        {
            setCurrentkey(data[0].key)
        }
    }, [data])

    // 在树的尾部追加一项
    function addDescription(){
        setData([...data, {
            key: String(data.length),
            title: '岗位能力',
            length: data.length,
            rate: 1,
            isEdit : false,
            content: ''
        }])
    }


    // 通过key找到当前项
    function searchItemByKey(array:IDescriptionData[], key: string) {
        for (let i=0; i<array.length; i++){
            let item = array[i];
            if (item.key == key){
                return item;
            }

            // 判断有没有子元素 如果有 回调
            if (item.children){

                let result = searchItemByKey(item.children, key) as IDescriptionData;
                if (Boolean(result)){
                    return result;
                }
            }
        }
        return undefined;
    }

    // 在当前树增加一个子树
    function addChildDescription(key: string){

        // 深拷贝一个
        let newData = [...data];

        // 将要加入的值
        let item = searchItemByKey(newData, key);
        
        

        let child = {
            key: `${key}-${++item!.length}`,
            title: '岗位能力',
            length: 0,
            rate: 1,
            isEdit : false,
            content: ''
        }

        // 如果有这个键值
        if (item!.children){
            item!.children.push(child);
        }else{
            // 没有则创建
            item!.children = [child];
        }
        setData(newData);
    }

    // 从父树中删掉当前树
    function removeChildDescription(key: string){

        // 深拷贝
        let newData = [...data];

        // 分割符
        let indexs = key.split('-');
        if (indexs.length === 1){
            // 删除顶层树
            newData.forEach((item,index)=>{
                if (item.key === key){
                    newData.splice(index, 1);
                }
            })
        }else{
            // 删除子树
            let item = searchItemByKey(newData, indexs.slice(0, indexs.length - 1).join('-'));
            item?.children?.forEach((value,index)=>{
                if (value.key === key){
                    item?.children!.splice(index, 1);
                }
            })
        }
        setData(newData);
    }

    // 修改title的输入框
    function editChildDescriptionTitle(key:string , status:boolean){
        console.log(key);
        let newData = [ ...data ];
        let item = searchItemByKey(newData , key);
        item!.isEdit = status;
        setData( newData )
    }

    // 修改title的值
    function cheangeTitleValue( key:string , value:string){
        console.log(key,value);
        let newData = [ ...data ];
        let item = searchItemByKey(newData , key);
        item!.title = value;
        setData( newData )
    }

    // selectCurrentkeyNode // 选中的树树枝
    function selectCurrentkeyNode(key: string){
        let item = searchItemByKey(data , key);
        setCurrentkey(item!.key);
        console.log(item);
        
    }

    // 修改评分
    function changeCurrentRate( key : string , rate : number){
        console.log(key,rate);
        let newData = [ ...data ];
        let item = searchItemByKey(newData , key);
        item!.rate = rate;
        setData( newData )
    }

    function handleChange(key : string , value : string){
        console.log(key,value);
        
        let newData = [ ...data ];
        let item = searchItemByKey(newData , key);
        item!.content = value;
        setData( newData )
    }

    return <div>
        {/* 左边树形结构 */}
        <section>
            <section>
                <Search style={{ marginBottom: 8 }} placeholder="清输入内容" />
                <Button onClick={()=>addDescription()}>+</Button>
            </section>
            <Tree
                autoExpandParent={true}
                treeData={data}
                titleRender={(nodeData : any)=>{
                    return <p
                            onClick={()=>{
                                selectCurrentkeyNode(nodeData.key)
                            }}
                        >
                        {/* <span>{JSON.stringify(nodeData)}</span> */}
                        { nodeData.isEdit? 
                            <input type="text" 
                                value={ nodeData.title } 
                                onChange={(e)=>{cheangeTitleValue(nodeData.key , e.target.value )}} 
                                onKeyDown={e=>{
                                    if(e.keyCode == 13)
                                    {
                                        editChildDescriptionTitle(String(nodeData.key) , false );
                                    }
                                }}
                                onBlur={()=>{
                                    editChildDescriptionTitle(String(nodeData.key) , false );
                                }}
                            /> 
                            : <span>{nodeData.title}</span> 
                        }
                        
                        <FormOutlined onClick={()=>{editChildDescriptionTitle(String(nodeData.key) , true )}}/>
                        <PlusOutlined onClick={()=>addChildDescription(String(nodeData.key))}/>
                        <MinusOutlined onClick={()=>removeChildDescription(String(nodeData.key))}/>
                    </p>
                }}
            />
        </section>
        {/* 右边平分项和md编辑器 */}
        {Currentkey.length? <section>
            <Rate count={3} value={searchItemByKey( data , Currentkey)!.rate} defaultValue={1} onChange={value=>changeCurrentRate(Currentkey , value)}></Rate>
            <Editor value={searchItemByKey( data , Currentkey)!.content} onChange={value =>handleChange( Currentkey , value)}></Editor>
        </section> : null} 
        
    </div>  
}

export default SkillDescription;